package com.bocai.yuweiwangluo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bocai.yuweiwangluo.R;
import com.bocai.yuweiwangluo.View.AutoScrollViewPager;
import com.bocai.yuweiwangluo.View.LoopViewPager;
import com.bocai.yuweiwangluo.activity.GameActivity;
import com.bocai.yuweiwangluo.activity.MatchActivity;
import com.bocai.yuweiwangluo.activity.MessageCenterActivity;
import com.bocai.yuweiwangluo.activity.SearchVenueActivity;
import com.bocai.yuweiwangluo.activity.VenueActivity;
import com.bocai.yuweiwangluo.base.BaseFragment;
import com.bocai.yuweiwangluo.bean.HomeBean;
import com.bocai.yuweiwangluo.net.MyOkHttpClient;
import com.bocai.yuweiwangluo.utils.MyConst;
import com.bocai.yuweiwangluo.utils.UrlData;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;


public class Fragment_Home extends BaseFragment implements View.OnClickListener {
    private static final int RESPONSE_SUCCEED = 1;
    private static final int RESPONSE_FAILED = 2;
    private TextView tv_home_recommend_venue,tv_home_nearby_venue,tv_home_all_venue;
    private LinearLayout ll_home_search,llRefresh;
    private FrameLayout fl_home_venue;
    private LinearLayout ll_home_banner;
    private LinearLayout ll_loading_data;
    private View view;
    private ImageView iv_title_right;
    private AutoScrollViewPager vp_home_advertisement,vp_venue;
    private List<View> dots; // 图片标题正文的那些点
    private List<View> dotsVenue; // 场馆的那些点
    // 定义的三个指示点
    private View dot0;
    private View dot1;
    private View dot2;
    private View dot3;
    private View dot4;
    private View dot5;
    private FragmentRecommendVenue mFragmentRecommendVenue;
    private FragmentNearbyVenue mFragmentNearbyVenue;
    private BannerAdapter mBannerAdapter;
    private HotVenueAdpter mVenueBannerAdapter;
    private HomeBean homeBean=new HomeBean();
    private LinearLayout ll_home_venue,ll_home_yuezhan,ll_home_game;
    private Handler handlerData=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            Gson gson = new Gson();
                switch (msg.what) {
                    case RESPONSE_SUCCEED:
                        Log.e("result", result);
                        homeBean = gson.fromJson(result, HomeBean.class);
                        hideLoading();
                        ll_loading_data.setVisibility(View.GONE);
                        if (homeBean.getHot().size()==2){
                            dot4.setVisibility(View.VISIBLE);
                            dotsVenue.add(dot4);
                        }
                        if(homeBean.getHot().size()==3){
                            dot4.setVisibility(View.VISIBLE);
                            dot5.setVisibility(View.VISIBLE);
                            dotsVenue.add(dot4);
                            dotsVenue.add(dot5);
                        }
                        setSelect(0);
                        startBanner();

                        break;
                    case RESPONSE_FAILED:
                        hideLoading();
                        llRefresh.setVisibility(View.VISIBLE);
                        showError(result);
                        break;
                }
        }
    };

    private void startBanner() {
        //hot场馆
        mVenueBannerAdapter=new HotVenueAdpter(getFragmentManager());
        vp_venue.setOnPageChangeListener(new MyPageChangeListener2());
        vp_venue.setAdapter(mVenueBannerAdapter);
//        vp_venue.startAutoScroll();
//        vp_venue.setInterval(5000);
        //广告banner
        mBannerAdapter=new BannerAdapter(getFragmentManager());
        vp_home_advertisement.setOnPageChangeListener(new MyPageChangeListener());
        vp_home_advertisement.setAdapter(mBannerAdapter);
        vp_home_advertisement.startAutoScroll();
        vp_home_advertisement.setInterval(5000);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        return view;
    }


//    @Override
//    public void onEventMainThread(MainEvent event) {
//        super.onEventMainThread(event);
//        if (event.msg.equals("location"))
//        {
//            getData();
//        }
//    }

    private void initView(View view)
    {
        getData();
        ll_loading_data=(LinearLayout)view.findViewById(R.id.ll_loading_data);
        llRefresh=(LinearLayout)view.findViewById(R.id.ll_refresh);
        ll_home_search=(LinearLayout)view.findViewById(R.id.ll_home_search);
        iv_title_right=(ImageView)view.findViewById(R.id.iv_title_right);
        tv_home_all_venue=(TextView)view.findViewById(R.id.tv_home_all_venue);
        ll_home_venue=(LinearLayout)view.findViewById(R.id.ll_home_venue);
        ll_home_yuezhan=(LinearLayout)view.findViewById(R.id.ll_home_yuezhan);
        ll_home_game=(LinearLayout)view.findViewById(R.id.ll_home_game);
        fl_home_venue=(FrameLayout)view.findViewById(R.id.fl_home_venue);
        tv_home_recommend_venue=(TextView)view.findViewById(R.id.tv_home_recommend_venue);
        tv_home_nearby_venue=(TextView)view.findViewById(R.id.tv_home_nearby_venue);
        dots = new ArrayList<View>();
        dotsVenue=new ArrayList<View>();
        dot0 = view.findViewById(R.id.v_dot0);
        dot1 = view.findViewById(R.id.v_dot1);
        dot2 = view.findViewById(R.id.v_dot2);
        dot3 = view.findViewById(R.id.v_dot3);
        dot4 = view.findViewById(R.id.v_dot4);
        dot5 = view.findViewById(R.id.v_dot5);
        dots.add(dot0);
        dots.add(dot1);
        dots.add(dot2);
        dotsVenue.add(dot3);
        vp_venue=(AutoScrollViewPager)view.findViewById(R.id.vp_venue);
        vp_home_advertisement=(AutoScrollViewPager)view.findViewById(R.id.vp_home_advertisement);

        initEvent();
    }

    /**
     * 获取首页数据
     */
    private void getData() {
        showLoading();
        MyOkHttpClient myOkHttpClient=new MyOkHttpClient(getActivity(),this);
        Log.e("location",MyConst.location_lat+"--------"+MyConst.location_lng+"");
        myOkHttpClient.getHomeData(UrlData.BASEURL + UrlData.HOME, MyConst.location_lng+"",MyConst.location_lat+"", handlerData);

    }

    private void initEvent() {
        vp_venue.setEnabled(false);
        vp_home_advertisement.setEnabled(false);
        llRefresh.setOnClickListener(this);
        ll_home_search.setOnClickListener(this);
        iv_title_right.setOnClickListener(this);
        tv_home_all_venue.setOnClickListener(this);
        ll_home_game.setOnClickListener(this);
        ll_home_venue.setOnClickListener(this);
        ll_home_yuezhan.setOnClickListener(this);
        tv_home_recommend_venue.setOnClickListener(this);
        tv_home_nearby_venue.setOnClickListener(this);
    }

    private void  initTextColor(){
        tv_home_recommend_venue.setTextColor(getResources().getColor(R.color.black));
        tv_home_nearby_venue.setTextColor(getResources().getColor(R.color.black));
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_refresh:
                llRefresh.setVisibility(View.GONE);
                getData();
                break;

            //推荐场馆
            case R.id.tv_home_recommend_venue :
                initTextColor();
                tv_home_recommend_venue.setTextColor(getResources().getColor(R.color.title_bag));
                setSelect(0);
                break;
            //附近场馆
            case R.id.tv_home_nearby_venue:
                initTextColor();
                tv_home_nearby_venue.setTextColor(getResources().getColor(R.color.title_bag));
                setSelect(1);
                break;
            case R.id.ll_home_game:
                startActivity(new Intent(getActivity(), GameActivity.class));
                break;
            case R.id.ll_home_venue:
                startActivity(new Intent(getActivity(), VenueActivity.class));
                break;
            case R.id.ll_home_yuezhan:
                startActivity(new Intent(getActivity(), MatchActivity.class));
                break;
            case R.id.tv_home_all_venue:
                startActivity(new Intent(getActivity(), VenueActivity.class));
                break;
            case R.id.iv_title_right:
                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                break;
            case R.id.ll_home_search:
                startActivity(new Intent(getActivity(), SearchVenueActivity.class));
                break;
        }
    }
    public void setSelect(int i) {
        FragmentManager fm =getActivity().getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);
        switch (i) {
            case 0:
                if (mFragmentRecommendVenue == null) {
                    mFragmentRecommendVenue = new FragmentRecommendVenue();

                    transaction.add(R.id.fl_home_venue, mFragmentRecommendVenue);
                } else {
                    transaction.show(mFragmentRecommendVenue);
                }
                mFragmentRecommendVenue.getData(homeBean.getRecommand());
                break;
            case 1:
                if (mFragmentNearbyVenue == null) {
                    mFragmentNearbyVenue = new FragmentNearbyVenue();
                    transaction.add(R.id.fl_home_venue, mFragmentNearbyVenue);
                } else {
                    transaction.show(mFragmentNearbyVenue);
                }
                mFragmentNearbyVenue.getData(homeBean.getMin());
                break;
        }
        transaction.commit();
    }
    private void hideFragment(FragmentTransaction transaction)
    {
        if (mFragmentRecommendVenue != null)
        {
            transaction.hide(mFragmentRecommendVenue);
        }
        if (mFragmentNearbyVenue != null)
        {
            transaction.hide(mFragmentNearbyVenue);
        }


    }
    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
    @Override
    public void onResume()
    {
        super.onResume();
    }

    @Override
    public void onStop()
    {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private class MyPageChangeListener implements LoopViewPager.OnPageChangeListener
    {

        private int oldPosition = 0;

        @Override
        public void onPageScrollStateChanged(int arg0)
        {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {

        }

        @Override
        public void onPageSelected(int position)
        {
            position = (homeBean.getBanner().size() + position%homeBean.getBanner().size())%homeBean.getBanner().size();
            dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
            dots.get(position).setBackgroundResource(R.drawable.dot_focused2);
            oldPosition = position;
        }
    }
    private class MyPageChangeListener2 implements LoopViewPager.OnPageChangeListener
    {

        private int oldPositionVenue = 0;

        @Override
        public void onPageScrollStateChanged(int arg0)
        {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {

        }

        @Override
        public void onPageSelected(int position)
        {
            position = (homeBean.getHot().size() + position%homeBean.getHot().size())%homeBean.getHot().size();
            dotsVenue.get(oldPositionVenue).setBackgroundResource(R.drawable.dot_focused);
            dotsVenue.get(position).setBackgroundResource(R.drawable.dot_focused2);
            oldPositionVenue = position;

        }
    }
    class BannerAdapter extends FragmentPagerAdapter {

        public BannerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            position = (homeBean.getBanner().size() + position%homeBean.getBanner().size())%homeBean.getBanner().size();
            BannerFrag fragment = new BannerFrag();
            fragment.getData(homeBean.getBanner().get(position));
            return fragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return homeBean.getBanner().get(position % homeBean.getBanner().size()).getPic().toUpperCase();
        }

        @Override
        public int getCount() {
            return homeBean.getBanner().size();
        }
    }
    class HotVenueAdpter extends FragmentPagerAdapter {

        public HotVenueAdpter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            position = (homeBean.getHot().size() + position%homeBean.getHot().size())%homeBean.getHot().size();
            HotVenueFrag fragment = new HotVenueFrag();
            fragment.getData(homeBean.getHot().get(position));
            return fragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return homeBean.getHot().get(position % homeBean.getHot().size()).getTitle().toUpperCase();
        }

        @Override
        public int getCount() {
            return homeBean.getHot().size();
        }
    }
}
